 ///
 /// @file    server.cc
 /// @author  lemon(haohb13@gmail.com)
 /// @date    2016-03-22 10:13:03
 ///
 
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <iostream>


int main(void)
{
	int listenfd = socket(AF_INET, SOCK_STREAM, 0);
	if(-1 == listenfd)
	{
		perror("socket");
		exit(EXIT_FAILURE);
	}

	struct sockaddr_in serverAddr;
	memset(&serverAddr, 0, sizeof(sockaddr_in));
	serverAddr.sin_family = AF_INET;
	serverAddr.sin_port = htons(8888);
	serverAddr.sin_addr.s_addr = INADDR_ANY;//代表本机地址
	
	int ret = bind(listenfd, 
				   (struct sockaddr *)&serverAddr,
				   sizeof(struct sockaddr));
	if(-1 == ret)
	{
		perror("bind");
		close(listenfd);
		exit(EXIT_FAILURE);
	}

	ret = listen(listenfd, 10);
	if(-1 == ret)
	{
		perror("listen");
		close(listenfd);
		exit(EXIT_FAILURE);
	}
	
	int connectFd = accept(listenfd, NULL, NULL);
	
	char buff[1024] = "welcome to server.";
	ret = write(connectFd, buff, strlen(buff));
	
	while(true)
	{
		memset(buff, 0, 1024);
		ret = read(connectFd, buff, 1024);
		ret = write(connectFd, buff, strlen(buff));
	}
	
	return 0;
}
